const express = require('express');
const router = express.Router();
const userModel = require('../../models/userModel')
const md5 = require('md5')
const jwt = require('jsonwebtoken')



router.post('/login', (req, res) => {
  const {username,password} = req.body
  userModel.findOne({username:username,password:md5(password)})
    .then((data) => {
    if (!data){
     return  res.json({
        code:'2001',
        msg:'用户名或密码错误',
        data:null
      })
    }
    else {
      //生成用户token
      let token = jwt.sign({
        username:username,
        _id:data._id
      },'wab',{expiresIn:60*60*24*7})
      res.json({
        code:'0000',
        msg:'登录成功',
        data:token
      })

    }
  })
    .catch((err) => {
      res.status(500)
      res.json({
        code:'2001',
        msg:'fail',
        data:null
      })
    })

})


//用户退出
router.post('/logout',(req, res) => {
  req.session.destroy(() => {
    res.render('success', {msg:'退出成功', url:'/login'})
  })
})

module.exports = router;
